Ext.application({
	name: 'Triends',
	controllers: ['Controller'],
	views: ['Login', 'MainPage', 'Tinglist', 'Tinginfo', 'AttendeeList',  
			'TingComment', 'Sendmessage', 'TingOpen', 'TingModify',
			'TriendsList',
			'Othersinfo', 'OtherTinglist',
			 'Userinfo', 'UserTinglist', 'UserinfoModify', 'Join', 'Mymessage', 'Mymessageinfo', 'AgreementConfirm', 
			'Settings', 'VersionPage', 'Noticelist', 'Noticeinfo', 'HelpPage', 'QuestionPage', 'PushPage'],
    launch: function() {
    	Webtest()
        // Test end!
        
    	document.addEventListener('deviceready', function() {
    		try {
    			
    			FB.init({ appId: "221973064597313", nativeInterface: CDV.FB, useCachedDialogs: false });

				FB.getLoginStatus(function(response) {
  					if (response.status == 'connected') {
				    	// the user is logged in and has authenticated your
				    	// app, and response.authResponse supplies
					    // the user's ID, a valid access token, a signed
					    // request, and the time the access token 
					    // and signed request each expire
//    					var uid = response.authResponse.userID;
    					var accessToken = response.authResponse.accessToken;
  						FB.Event.subscribe('auth.login', autologin(accessToken));
  					} else {
						Triends.app.getHistory().add(
							Ext.create('Ext.app.Action', {url: 'login'})
						);
  					}
 				});
            	
            	document.addEventListener("backbutton", Ext.bind(onBackKeyDown, Triends), true);
   				
            	function onBackKeyDown(e) {
            		e.preventDefault();
            		
            		if (Ext.typeOf(Ext.Viewport.child('mask')) == 'object') {
            			Ext.Viewport.child('mask').fireEvent('tap');
            		} else if ( Triends.app.getHistory().getToken() == 'mainpage' || Triends.app.getHistory().getToken() == 'login') {
            			navigator.notification.confirm(
							'Triends를 종료하시겠습니까?',
							function(buttonIndex){
								if (buttonIndex == 1) {
	       							navigator.app.exitApp();
								} else if (buttonIndex == 2) {
       								Ext.emptyFn
       							}
							},
							'알림',
							'OK, Cancel'
						)
            		} else {
            			navigator.app.backHistory();
            		}           		
            	}
        	} catch (e) {
            	alert(e);
 	    	}
    	}, false); 
    }
});

var deviceID;  // Logout 할 때 DB의 기기 등록정보에서 해당 디바이드 번호만 삭제하기 위함.

function autologin(accessToken) {
	Ext.Viewport.setMasked({
		xtype: 'loadmask',
		message: '로그인 중입니다.',
		indicator: true
	});
	FB.api('/me?access_token='+accessToken, function(response) {
	
		Ext.create('mainpage');
		Triends.app.getHistory().add(Ext.create('Ext.app.Action', {url: 'mainpage'}));
		
		var UserStore = Ext.getStore('UserStore');
		UserStore.getProxy().setExtraParams({id: response.id});  
		UserStore.load({
			callback: function(records, operation, success) {
				MainDataLoad();
			}
		});
	});	
}

function MainDataLoad() {  // app.js, Login.js, Join.js 에서 사용
	Ext.Viewport.setMasked(false);
	Ext.Viewport.setMasked({
		xtype: 'loadmask',
		message: 'Loading...',
		indicator: true
	});
	
	
	navigator.geolocation.getCurrentPosition(function(position){
						
		UserStore.getAt(0).data.UserLat = position.coords.latitude;
		UserStore.getAt(0).data.UserLng = position.coords.longitude;
   		var userlat = UserStore.getAt(0).data.UserLat
       	var userlng = UserStore.getAt(0).data.UserLng
       	var userlatlng = new google.maps.LatLng(userlat, userlng);
       	var userid = UserStore.getAt(0).data.ID;
		var usertheme = UserStore.getAt(0).data.UserTheme;
		
		
		geocoder.geocode({'latLng':userlatlng}, function(results, status){
			if (status == google.maps.GeocoderStatus.OK) {
				if (results[1]) {
					var usercityname = results[1].address_components[2].long_name;
					var userlocationpanel = Ext.getCmp('userlocationpanel');
					userlocationpanel.setHtml("<font size='2'>"+usercityname+"</font>");
				}
			}
		});
       	
		if (usertheme == 1) {  // usertheme이 1인 경우 triendslisttheme에서 change이벤트가 발생하지 않기 때문.
			Ext.getCmp('tingthemeimg').setHtml('<img src="resource/images/'+usertheme+'.png" width="25px" height="25px">');
			Ext.getCmp('triendstheme').setHtml('<img src="resource/images/'+usertheme+'.png" width="25px" height="25px">');
			var userthemepanel = Ext.getCmp('userthemepanel');
			userthemepanel.setSrc('resource/images/'+usertheme+'.png');
		} else {
			Ext.getCmp('triendslisttheme').setValue(usertheme);
		}
		
       	TriendsStore.setProxy({
			type: "jsonp",
			url: 'http://itscreater.cafe24.com/Triends/TriendsList.jsp',
			callbackkey: 'callback',
			extraParams: {
				userid: userid,
				userlat:userlat,
    			userlng:userlng,
    			usertheme: usertheme
			},
			pageParam: 'pages',
			limitParam: 'rpp',
			reader: {
				type: "json",
				rootProperty: "results",
				totalProperty: "total"
			}
		});
					
		tingStore.setProxy({
			type: "jsonp",
			url: 'http://itscreater.cafe24.com/Triends/TingList.jsp',
			extraParams: {
				userlat: userlat, 
				userlng:userlng, 
				usertheme: usertheme
			},
			callbackkey: 'callback',
			pageParam: 'pages',
			limitParam: 'rpp',
			reader: {
				type: "json",
				rootProperty: "results",
				totalProperty: "total"
			}
		});
		
			Ext.data.JsonP.request({
			url: 'http://itscreater.cafe24.com/Triends/UserThemeUpdate.jsp',
			params: {
				userid: userid,
				userlat:userlat,
				userlng:userlng,
				usertheme: usertheme
			},
			callbackKey: 'callback',
			success: function(result) {
				TriendsStore.loadPage(1, {
					callback: function() {
						tingStore.loadPage(1)
						var userimg = Ext.getCmp('userimg');
						userimg.setHtml("<img src='https://graph.facebook.com/"+userid+"/picture?width=130&height=130'>");
				
						var userHOSTtingStore = Ext.getStore('userHOSTtingstore');
						var userATTENDtingStore = Ext.getStore('userATTENDtingstore');	
						
						Ext.data.JsonP.request({
							url: 'http://itscreater.cafe24.com/Triends/UserHostTing.jsp',
							params:{
								id: userid, 
								userlat: userlat, 
								userlng: userlng, 
								usertheme: usertheme
							},
							callbackKey: 'callback',
							success: function(result) {
								for(i=0;i<result.length;i++){
									var date = result[i].DATE.split(' ')[0];
									var hour = result[i].DATE.split(' ')[1].substr(0,2);
									var minute = result[i].DATE.split(' ')[1].substr(2);
									var ampm;
									if(hour >= 12){
										hour = hour-12;
										ampm = "PM"
									} else{
										ampm = "AM"
									}
									var finaldate = date+" "+ampm+" "+hour+""+minute;
									result[i].AMPMDATE = finaldate; 
								}
								userHOSTtingStore.setData(result);
								
								Ext.data.JsonP.request({
									url: 'http://itscreater.cafe24.com/Triends/UserAttendTing.jsp',
									params:{
										id: userid, 
										userlat: userlat, 
										userlng: userlng, 
										usertheme: usertheme
									},
									callbackKey: 'callback',
									success: function(result) {
										for(i=0;i<result.length;i++){
											var date = result[i].DATE.split(' ')[0];
											var hour = result[i].DATE.split(' ')[1].substr(0,2);
											var minute = result[i].DATE.split(' ')[1].substr(2);
											var ampm;
											if(hour >= 12){
												hour = hour-12;
												ampm = "PM"
											} else{
												ampm = "AM"
											}
											var finaldate = date+" "+ampm+" "+hour+""+minute;
											result[i].AMPMDATE = finaldate;
										}
										userATTENDtingStore.setData(result);
										
										var msgStore = Ext.getStore('msgstore');
										msgStore.getProxy().setExtraParams({id: userid});
										msgStore.load();
						
										window.GCM.register("157631774206", "GCM_Event", GCM_Success, GCM_Fail );
										
										setTimeout(function() {
											Ext.Viewport.setMasked(false);
										}, 500);
									}
								});
							}
						});									
					}
				});
			}
		});
	}, function(error) {console.log(error.code+error.message)});
}

function GCM_Event(e) {

  switch( e.event )
  {
  case 'registered':
  	var UserStore = Ext.getStore('UserStore');
  	var userid = UserStore.getAt(0).data.ID;
    // the definition of the e variable is json return defined in GCMReceiver.java
    // In my case on registered I have EVENT and REGID defined
    deviceID = e.regid;
    Ext.data.JsonP.request({
    	url: 'http://itscreater.cafe24.com/Triends/gcminsert.jsp',
      	params: {
      		id: userid,
      		regid: e.regid,
      		device: 0
      	},
      	callbackKey: 'callback'
      })

    break;

  default:
    alert('<li>EVENT -> Unknown, an event was received and we do not know what it is</li>');

    break;
  }
}
				
function GCM_Success(e) {
//	alert('<li>GCM_Success -> We have successfully registered and called the GCM plugin, waiting for GCM_Event:registered -> REGID back from Google</li>');

}
				
function GCM_Fail(e) {
//				  alert('<li>GCM_Fail -> GCM plugin failed to register</li>');

//				  alert('<li>GCM_Fail -> ' + e.msg + '</li>');

}

function Webtest() {
	
	
	Ext.create('mainpage');
	Triends.app.getHistory().add(Ext.create('Ext.app.Action', {url: 'mainpage'}));

	var UserStore = Ext.getStore('UserStore');
	UserStore.getProxy().setExtraParams({id: '100001772264931'});  //response.id
	UserStore.load({
	callback: function(records, operation, success) {
		navigator.geolocation.getCurrentPosition(function(position){
			
			UserStore.getAt(0).data.UserLat = position.coords.latitude;
			UserStore.getAt(0).data.UserLng = position.coords.longitude;
       		var userlat = UserStore.getAt(0).data.UserLat;
           	var userlng = UserStore.getAt(0).data.UserLng;
           	var userlatlng = new google.maps.LatLng(userlat, userlng);
           	var userid = UserStore.getAt(0).data.ID;
			var usertheme = UserStore.getAt(0).data.UserTheme;
			geocoder.geocode({'latLng':userlatlng}, function(results, status){
				if (status == google.maps.GeocoderStatus.OK) {
					if (results[1]) {
						var usercityname = results[1].address_components[2].long_name;
						var userlocationpanel = Ext.getCmp('userlocationpanel');
						userlocationpanel.setHtml("<font size='2'>"+usercityname+"</font>");
					}
				}
			});
			
			if (usertheme == 1) {  // usertheme이 1인 경우 triendslisttheme에서 change이벤트가 발생하지 않기 때문.
			Ext.getCmp('tingthemeimg').setHtml('<img src="resource/images/'+usertheme+'.png" width="25px" height="25px">');
			Ext.getCmp('triendstheme').setHtml('<img src="resource/images/'+usertheme+'.png" width="25px" height="25px">');
			var userthemepanel = Ext.getCmp('userthemepanel');
			userthemepanel.setSrc('resource/images/'+usertheme+'.png');
		} else {
			Ext.getCmp('triendslisttheme').setValue(usertheme);
		}
			
           	TriendsStore.setProxy({
				type: "jsonp",
				url: 'http://itscreater.cafe24.com/Triends/TriendsList.jsp',
				callbackkey: 'callback',
				extraParams: {
					userid: userid,
					userlat:userlat,
        			userlng:userlng,
        			usertheme: usertheme
				},
				pageParam: 'pages',
				limitParam: 'rpp',
				reader: {
					type: "json",
					rootProperty: "results",
					totalProperty: "total"
				}
			});
						
    		tingStore.setProxy({
				type: "jsonp",
				url: 'http://itscreater.cafe24.com/Triends/TingList.jsp',
				extraParams: {
					userlat: userlat, 
					userlng:userlng, 
					usertheme: usertheme
				},
				callbackkey: 'callback',
				pageParam: 'pages',
				limitParam: 'rpp',
				reader: {
					type: "json",
					rootProperty: "results",
					totalProperty: "total"
				}
			});
			TriendsStore.loadPage(1);
			tingStore.loadPage(1);
			
			
			var userimg = Ext.getCmp('userimg');
			userimg.setHtml("<img src='https://graph.facebook.com/"+userid+"/picture?width=130&height=130'>");

			var userHOSTtingStore = Ext.getStore('userHOSTtingstore');
			Ext.data.JsonP.request({
				url: 'http://itscreater.cafe24.com/Triends/UserHostTing.jsp',
				params:{
					id: userid, 
					userlat: userlat, 
					userlng: userlng, 
					usertheme: usertheme
				},
				callbackKey: 'callback',
				success: function(result) {
					for(i=0;i<result.length;i++){
						var date = result[i].DATE.split(' ')[0];
						var hour = result[i].DATE.split(' ')[1].substr(0,2);
						var minute = result[i].DATE.split(' ')[1].substr(2);
						var ampm;
						if(hour >= 12){
							hour = hour-12;
							ampm = "PM"
						} else{
							ampm = "AM"
						}
						var finaldate = date+" "+ampm+" "+hour+""+minute;
						result[i].AMPMDATE = finaldate; 
					}
					userHOSTtingStore.setData(result);
				}
			});
			var userATTENDtingStore = Ext.getStore('userATTENDtingstore');		
			Ext.data.JsonP.request({
				url: 'http://itscreater.cafe24.com/Triends/UserAttendTing.jsp',
				params:{
					id: userid, 
					userlat: userlat, 
					userlng: userlng, 
					usertheme: usertheme
				},
				callbackKey: 'callback',
				success: function(result) {
					for(i=0;i<result.length;i++){
						var date = result[i].DATE.split(' ')[0];
						var hour = result[i].DATE.split(' ')[1].substr(0,2);
						var minute = result[i].DATE.split(' ')[1].substr(2);
						var ampm;
						if(hour >= 12){
							hour = hour-12;
							ampm = "PM"
						} else{
							ampm = "AM"
						}
						var finaldate = date+" "+ampm+" "+hour+""+minute;
						result[i].AMPMDATE = finaldate;
					}
					userATTENDtingStore.setData(result);
				}
			});
			var msgStore = Ext.getStore('msgstore');
			msgStore.getProxy().setExtraParams({id: userid});
			msgStore.load();
			
//			var scrollables = document.querySelectorAll('.x-scroll-container');
//				for(i=0;i<scrollables.length;i++) {
//					var unloader = new Unloader(scrollables[i], '.x-data-item');
//					var iscroll = new iScroll(scrollables[i],  {
//					    onRefresh: function() {
//					        unloader.setup(this.x, this.y);
//					    },
//					    onPositionChange: function(x, y) {
//				        	unloader.onmove(x, y); 
//				    	}
//					});
//					setTimeout(function() {
//					iscroll.refresh();
//					Ext.getCmp('triendslist').getScrollable().getScroller().fireEvent('refresh');
//				}, 5000)
//				}
				
		}, function(error) {console.log(error.code+error.message)});
	            			
		}
	});
}